import com.google.common.collect.Maps;
import com.itextpdf.text.DocumentException;
import org.w3c.tidy.Tidy;

import java.io.*;
import java.util.Iterator;
import java.util.Map;

/**
 * @author cww
 * Created by cww
 * Date : 2018/2/9
 */
public class HtmlToPdfUtilsTestJar {
    private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
    private static final String HTML_TEMP_NAME = "htmlTemp";
    private static final String CHANGE_FLAG = "changeFlag";
    private static final String PDF_TEMP_NAME = "pdfTemp";
    private static final String SYSTEM_PATH = "os.name";
    private static final String FORMAT_TYPE = "UTF-8";
    private static final String HTML_SUFFIX = ".html";
    private static final String PDF_SUFFIX = ".pdf";
    private static final String DIR_SYMBOL = "/";

    public static void main(String[] args) {
        String content = args[0];
        System.out.println(content);
        Map<String,Object> result;
        result = new HtmlToPdfUtilsTestJar().convert("<p>jfiefeifejifej&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;<span style=\"font-family: 楷体, 楷体_GB2312, SimKai;\">这是楷体&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;<span style=\"font-family: 隶书, SimLi;\">这是隶书&nbsp; &nbsp; &nbsp;&nbsp;<span style=\"font-family: 微软雅黑, &quot;Microsoft YaHei&quot;;\">这是微软雅黑</span></span></span></p><p><span style=\"font-family: 楷体, 楷体_GB2312, SimKai;\">这是楷体</span></p><p><span style=\"font-family: 楷体, 楷体_GB2312, SimKai;\">这是黑体<img src=\"http://yqb-test.oss-cn-shenzhen.aliyuncs.com/yqb_upload_local/richtxt/dbdca64e8de94f378f40011bae77120b.png\" title=\"cache2\"/></span></p><p><span style=\"font-family: 微软雅黑, &quot;Microsoft YaHei&quot;;\">这是微软雅黑</span></p><p><span style=\"font-family: 隶书, SimLi;\">这是隶书</span></p><p><span style=\"font-family: &quot;arial black&quot;, &quot;avant garde&quot;;\">this is</span></p><p><span style=\"font-family: &quot;arial black&quot;, &quot;avant garde&quot;;\"></span></p><p style=\"white-space: normal;\"><span style=\"font-family: 微软雅黑, &quot;Microsoft YaHei&quot;;\">这是微软雅黑</span></p><p style=\"white-space: normal;\"><span style=\"font-family: 隶书, SimLi;\">这是隶书</span></p><p style=\"white-space: normal;\"><span style=\"font-family: &quot;arial black&quot;, &quot;avant garde&quot;;\">this is</span></p><p><span style=\"font-family: &quot;arial black&quot;, &quot;avant garde&quot;;\"><br/></span></p><p><span style=\"font-family: &quot;arial black&quot;, &quot;avant garde&quot;;\"></span></p><p style=\"white-space: normal;\"><span style=\"font-family: 微软雅黑, &quot;Microsoft YaHei&quot;;\">这是微软雅黑</span></p><p style=\"white-space: normal;\"><span style=\"font-family: 隶书, SimLi;\">这是隶书</span></p><p style=\"white-space: normal;\"><span style=\"font-family: &quot;arial black&quot;, &quot;avant garde&quot;;\">this is</span></p><p style=\"white-space: normal;\"><span style=\"font-family: 微软雅黑, &quot;Microsoft YaHei&quot;;\">这是微软雅黑</span></p><p style=\"white-space: normal;\"><span style=\"font-family: 隶书, SimLi;\">这是隶书</span></p><p style=\"white-space: normal;\"><span style=\"font-family: &quot;arial black&quot;, &quot;avant garde&quot;;\">this is</span></p><p style=\"white-space: normal;\"><span style=\"font-family: 微软雅黑, &quot;Microsoft YaHei&quot;;\">这是微软雅黑</span></p><p style=\"white-space: normal;\"><span style=\"font-family: 隶书, SimLi;\">这是隶书</span></p><p style=\"white-space: normal;\"><span style=\"font-family: &quot;arial black&quot;, &quot;avant garde&quot;;\">this is</span></p><p><span style=\"font-family: &quot;arial black&quot;, &quot;avant garde&quot;;\"><img src=\"http://yqb-test.oss-cn-shenzhen.aliyuncs.com/yqb_upload_local/richtxt/dbdca64e8de94f378f40011bae77120b.png\" title=\"cache2\" style=\"font-family: 楷体, 楷体_GB2312, SimKai; white-space: normal;\"/>额凤飞飞<img src=\"http://yqb-test.oss-cn-shenzhen.aliyuncs.com/yqb_upload_local/richtxt/dbdca64e8de94f378f40011bae77120b.png\" title=\"cache2\" style=\"font-family: 楷体, 楷体_GB2312, SimKai; white-space: normal;\"/></span><br/></p><p><span style=\"font-family: &quot;arial black&quot;, &quot;avant garde&quot;;\"><img src=\"http://yqb-test.oss-cn-shenzhen.aliyuncs.com/yqb_upload_local/richtxt/429bef0ad2dd4223aa01e36a57c10809.png\" title=\"JWT流程\"/></span></p>");
        Iterator<Map.Entry<String,Object>> resultIT = result.entrySet().iterator();
        while (resultIT.hasNext()){
            Map.Entry<String,Object> entry = resultIT.next();
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
        System.out.println("执行成功");
    }

    /**
     * 1.组装临时文件目录
     * 2.检查是否有相关历史temp文件
     * 3.存储html临时文件,注意格式设定
     * 4.html转换为pdf
     * 5.PDF临时文件上传oss
     * 6.删除PDF、HTML临时文件
     *
     * 注意：传入的html字符串需要是格式转义后的！！！
     * 参考：String content = URLDecoder.decode(htmlContent, "UTF-8");
     * @param content
     * @return
     */
    public Map<String, Object> convert(String content){
        Map<String ,Object> resultMap = Maps.newHashMap();
        try {
            //组装临时文件目录，页面传过来的html内容存到系统的temp目录
            String htmlTemp;
            String pdfTemp;
            if (System.getProperty(SYSTEM_PATH).toUpperCase().contains("WINDOWS")){
                //windows下读取的tmp目录为"\tmp\"，而使用的时候要换位为"/"
                htmlTemp = (System.getProperty(JAVA_IO_TMPDIR)+ HTML_TEMP_NAME + HTML_SUFFIX).replace("\\","/");
                pdfTemp = (System.getProperty(JAVA_IO_TMPDIR)+ PDF_TEMP_NAME + PDF_SUFFIX).replace("\\","/");
            }else if (System.getProperty(SYSTEM_PATH).toUpperCase().contains("LINUX")){
                //linux下取出的tmp目录为"tmp",前面需要加个"/"
                htmlTemp = (System.getProperty(JAVA_IO_TMPDIR)+ DIR_SYMBOL + HTML_TEMP_NAME + HTML_SUFFIX);
                pdfTemp = (System.getProperty(JAVA_IO_TMPDIR)+ DIR_SYMBOL + PDF_TEMP_NAME + PDF_SUFFIX);
            }else {
                resultMap.put(CHANGE_FLAG, false);
                System.out.println("不支持的系统路径");
                return resultMap;
            }
            //先检查temp目录下的htmlTemp.html是否存在，如果存在需要先删除
            File htmlTempFile = new File(htmlTemp);
            if (htmlTempFile.exists()){
                System.out.println("删除历史未删除的临时html文件");
                deleteTmp(htmlTemp);
            }

            //存储html临时文件
            //html头部的格式必须定义，否者转换会出现乱码
            content = "<meta content=\"text/html; charset=utf-8\" http-equiv=\"content-type\" />"+content;
            saveHtml(content,htmlTemp);

            //html转换为pdf
            createPdf(pdfTemp,htmlTemp);

            System.out.println("html to pdfTemp success");

            //PDF临时文件上传oss
//            resultMap =  upLoadPdf(pdfTemp);
            //删除PDF临时文件
            deleteTmp(pdfTemp);
            System.out.println("删除临时pdf文件"+pdfTemp);
            //删除HTML临时文件
            deleteTmp(htmlTemp);
            System.out.println("删除临时html文件"+htmlTemp);

        } catch (Exception e) {
            System.out.println("HTML转PDF异常");
            resultMap.put(CHANGE_FLAG, false);
        }
        return resultMap;
    }

    /**
     * 删除文件
     * @param tempFile 文件路径
     */
    private void deleteTmp(String tempFile){
        try {
            File fileDelete = new File(tempFile);
            if (fileDelete.exists()){
                fileDelete.delete();
            } else {
                System.out.println("删除生成的临时文件异常");
            }
        } catch (Exception e) {
            System.out.println("删除生成的临时文件异常");
        }
    }

    /**
     * 对html内容进行格式化并且保存
     * @param content html内容
     * @param tempDir html存储位置
     */
    private void saveHtml(String content, String tempDir) throws IOException {
        Tidy tidy = new Tidy();
        InputStream inputStream1 = new ByteArrayInputStream(content.getBytes(FORMAT_TYPE));

        OutputStream os2 = new FileOutputStream(new File(tempDir));
        // 设定输出为xhtml(还可以输出为xml)
        tidy.setXHTML(true);
        //关闭控制台警告
        tidy.setShowWarnings(false);
        tidy.setInputEncoding(FORMAT_TYPE);
        tidy.setOutputEncoding(FORMAT_TYPE);
        // 不设置它会在输出的文件中给加条meta信息
        tidy.setTidyMark(false);
        // 让它加上<?xml version="1.0"?>
        tidy.setXmlPi(true);
        // 缩进，可以省略，只是让格式看起来漂亮
        tidy.setIndentContent(true);
        tidy.parse(inputStream1, os2);

        inputStream1.close();
        os2.close();
    }

    /**
     * 调用系统命令将html文件转为pdf
     * 注意1：html文件中需要带上格式
     * 注意2：在调试过程中发现Windows系统下隶书会出现乱码，但linux系统下只要有字体在字体目录下，就不会出现该情况
     * @param htmlTempFile html temp文件临时存储路径，用于转换为pdf，转换成功后应该删除
     * @param pdfTempFile pdf临时存储文件，用于上传oss，上传后应该删除
     * @throws IOException
     * @throws DocumentException
     */
    private void createPdf(String pdfTempFile, String htmlTempFile) throws IOException, InterruptedException {
        //html文件转换为pdf
        StringBuilder cmd = new StringBuilder();
        //wkhtmltopdf运行路径在系统中的路径
        cmd.append("/usr/local/wkhtmltox/bin/wkhtmltopdf");
//        cmd.append("C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe");
        //空格是需要的，系统命令用空格进行分割
        cmd.append(" ");
        //根据路径或者http地址读取html
        cmd.append("file:///"+htmlTempFile);
        cmd.append(" ");
        //html生成pdf
        cmd.append(pdfTempFile);
        Process proc = Runtime.getRuntime().exec(cmd.toString());
        proc.waitFor();
    }

}
